package com.liqi.display.api;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.liqi.display.common.Constants;
import com.liqi.display.common.Results;
import com.liqi.display.common.SystemCode;
import com.liqi.display.entity.SystemParam;
import com.liqi.display.entity.returnType.TopEightTask;
import com.liqi.display.entity.Statistics;
import com.liqi.display.service.IStatisticsService;
import com.liqi.display.service.ISystemParamService;
import com.liqi.display.utils.CalculateUtil;
import com.liqi.display.utils.DateUtil;
import com.liqi.display.utils.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/display/statistics")
public class StatisticsController {

    private static final Logger logger = LoggerFactory.getLogger(StatisticsController.class);

    @Autowired
    RedisUtil redisUtil;
    @Autowired
    private IStatisticsService statisticsService;
    @Autowired
    private ISystemParamService systemParamService;

    /**
     * 1.当天业务量
     * @return
     */
    @RequestMapping("getBusinessDayTotal")
    public Statistics getBusinessDayTotal() {
        Statistics resultModel = new Statistics();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        //取号总数
        Integer numDayTotal = statisticsService.getNumDayTotal(sdf.format(DateUtil.getDay()),sdf.format(DateUtil.getCurrentDay()));
        //预约数
        Integer orderDayTotal = statisticsService.getOrderDayTotal(sdf.format(DateUtil.getDay()),sdf.format(DateUtil.getCurrentDay()));
        //现场取号数
        Integer xcNumDayTotal = statisticsService.getXCNumDayTotal(sdf.format(DateUtil.getDay()),sdf.format(DateUtil.getCurrentDay()));
        //预约取号数
        Integer yyNumDayTotal = statisticsService.getYYNumDayTotal(sdf.format(DateUtil.getDay()),sdf.format(DateUtil.getCurrentDay()));
        //当天收件总数
        Integer totalDeal = statisticsService.getTotalDeal(sdf.format(DateUtil.getDay()),sdf.format(DateUtil.getCurrentDay()));
        //当天发证总数
        Integer totalSend = statisticsService.getTotalSend(sdf.format(DateUtil.getDay()),sdf.format(DateUtil.getCurrentDay()));
        Map res=new HashMap<>();
        res.put("numDayTotal",numDayTotal);
        res.put("orderDayTotal",orderDayTotal);
        res.put("xcNumDayTotal",xcNumDayTotal);
        res.put("yyNumDayTotal",yyNumDayTotal);
        res.put("totalDeal",totalDeal);
        res.put("totalSend",totalSend);
        resultModel.setMapResult(0,"调用成功",res);
        logger.info("getBusinessDayTotal返回参数resultModel{}", JSON.toJSONString(resultModel));
        return resultModel;
    }

    /**
     * 2、近30天业务量统计
     * @return
     */
    @RequestMapping("getBusinessMouthTotal")
    public Statistics getBusinessMouthTotal() {
        Map res=new HashMap<>();
        Map map1=new HashMap();
        Map map2=new HashMap();
        Statistics resultModel=new Statistics();
        int notWorkDay = DateUtil.getNotWorkDay(30);
        String pattern = "yyyy-MM-dd";

        //30天每个工作日的收件量和办件量
        for (int i = 30+notWorkDay; i>0; i--) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date lateWorkDay = DateUtil.getLateWorkDay(i, 0, 0, 0);
            Date lateWorkDay1 = DateUtil.getLateWorkDay(i, 23, 59, 59);
            if (lateWorkDay != null && lateWorkDay1 != null) {
                String start = simpleDateFormat.format(lateWorkDay);
                String dateStart = sdf.format(lateWorkDay);
                String end = simpleDateFormat.format(lateWorkDay1);
                String dateEnd = sdf.format(lateWorkDay1);
                if (start != null && end != null) {
                    int num1 = statisticsService.getMouthTotalDeal(start, end);
                    map1.put(dateStart, num1);
                    int num2 = statisticsService.getMouthTotalSend(start, end);
                    map2.put(dateEnd, num2);
                }

            }
        }
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        String start = sdf.format(DateUtil.getLate(pattern,30,0,0,0));
        String end = sdf.format(DateUtil.getLate(pattern,0,23,59,59));
        //取号总数
        Integer numMouthTotal = statisticsService.getNumMouthTotal(start, end);
        //预约数
        Integer orderMouthTotal = statisticsService.getOrderMouthTotal(start, end);
        //现场取号数
        Integer xcNumMouthTotal = statisticsService.getXCNumMouthTotal(start, end);
        //预约取号数
        Integer yyNumMouthTotal = statisticsService.getYYNumMouthTotal(start, end);
        //收件总数
        Integer mouthTotalDeal = statisticsService.getMouthTotalDeal(start, end);
        //发证总数
        Integer mouthTotalSend = statisticsService.getMouthTotalSend(start, end);

        res.put("numMouthTotal",numMouthTotal);
        res.put("orderMouthTotal",orderMouthTotal);
        res.put("xcNumMouthTotal",xcNumMouthTotal);
        res.put("yyNumMouthTotal",yyNumMouthTotal);
        res.put("mouthTotalDeal",mouthTotalDeal);
        res.put("mouthTotalSend",mouthTotalSend);
        res.put("recentDeal",map1);
        res.put("recentSend",map2);
        resultModel.setMapResult(0,"调用成功",res);
        logger.info("getBusinessMouthTotal返回参数resultModel{}", JSON.toJSONString(resultModel));
        return resultModel;
    }

    //3、最近七天取票方式趋势图
    /**
     * 统计近七天的预约取号数
     * @return
     */
    @RequestMapping("getSevenOrder")
    public Results getSevenOrder() {
        Results results = new Results();
        try {
            Map<String, Integer> map = statisticsService.totalLateOrder();
            results.setCode(SystemCode.SYS_OK.getKey());
            results.setMessage(SystemCode.SYS_OK.getValue());
            results.setData(map);
            return results;
        } catch (Exception e) {
            results.setCode(SystemCode.SYS_FAIL.getKey());
            results.setMessage(SystemCode.SYS_FAIL.getValue());
            return results;
        }
    }
    /**
     * 统计近七天的现场取号数
     * @return
     */
    @RequestMapping("getSevenCurrent")
    public Results getSevenCurrent() {
        Results results = new Results();
        try {
            Map<String, Integer> map = statisticsService.totalLateCurrent();
            results.setCode(SystemCode.SYS_OK.getKey());
            results.setMessage(SystemCode.SYS_OK.getValue());
            results.setData(map);
            return results;
        } catch (Exception e) {
            results.setCode(SystemCode.SYS_FAIL.getKey());
            results.setMessage(SystemCode.SYS_FAIL.getValue());
            return results;
        }
    }

    //4、近30天各渠道申办量
    /**
     * 设置近30天各渠道申办量
     */
    @RequestMapping("acceptMethodCron")
    public Statistics acceptMethodCron(){
        Statistics resultModel = new Statistics();
        //Map<String, Integer> temp = new HashMap<>();
        Map<String, String> map = statisticsService.getWeekBidType();
        /*for (Map.Entry<String, Integer> m : map.entrySet()) {
            temp.put(m.getKey(),m.getValue()+Integer.valueOf(redisUtil.get(Constants.BASE_ACCEPT_METHOD_NUM)));
        }*/
        resultModel.setMapResult(0,"调用成功",map);
        return resultModel;
    }


    //5、各时段取号量柱状图
    /**
     * 设置各时段业务量柱状图的获取近7天近30天的办理人数
     */
    @RequestMapping("latelyAcceptNumCron")
    public Statistics latelyAcceptNumCron() {
        Map res=new HashMap<>();
        Statistics resultModel=new Statistics();
        try {
            //最近30天的每个时间端（取号数统计=人流量）
            //计算工作日
            int notWorkDay = DateUtil.getNotWorkDay(30);
            Date late30Date = DateUtil.getLateDate("yyyy-MM-dd HH:mm:ss", 30 + notWorkDay);
            // Date late30Date = DateUtil.getLateDate("yyyy-MM-dd HH:mm:ss",30);
            Map<Object,Object> late30DateMap = new HashMap<Object,Object>();
            late30DateMap.put("8:30~9:30",statisticsService.lateComare(late30Date,8));
            late30DateMap.put("9:30~10:30",statisticsService.lateComare(late30Date,9));
            late30DateMap.put("10:30~11:30",statisticsService.lateComare(late30Date,10));
            late30DateMap.put("11:30~12:00",statisticsService.lateComare(late30Date,11));
            late30DateMap.put("14:30~15:30",statisticsService.lateComare(late30Date,14));
            late30DateMap.put("15:30~16:30",statisticsService.lateComare(late30Date,15));
            late30DateMap.put("16:30~17:30",statisticsService.lateComare(late30Date,16));
            res.putAll(late30DateMap);

            //最近7天的每个时间端（取号数统计=人流量）
            //计算工作日
            int notWork7Day = DateUtil.getNotWorkDay(7);
            Date late7Date = DateUtil.getLateDate("yyyy-MM-dd HH:mm:ss", 7 + notWorkDay);
            //Date late7Date = DateUtil.getLateDate("yyyy-MM-dd HH:mm:ss",7);
            Map<Object,Object> late7DateMap = new HashMap<Object,Object>();
            late7DateMap.put("8:30~9:30",statisticsService.lateComare(late7Date,8));
            late7DateMap.put("9:30~10:30",statisticsService.lateComare(late7Date,9));
            late7DateMap.put("10:30~11:30",statisticsService.lateComare(late7Date,10));
            late7DateMap.put("11:00~12:00",statisticsService.lateComare(late7Date,11));
            late7DateMap.put("14:30~15:30",statisticsService.lateComare(late7Date,14));
            late7DateMap.put("15:30~16:30",statisticsService.lateComare(late7Date,15));
            late7DateMap.put("16:30~17:30",statisticsService.lateComare(late7Date,16));
            res.putAll(late7DateMap);
            resultModel.setMapResult(0,"调用成功",res);
            return resultModel;
        }catch (Exception e) {
            e.printStackTrace();
            resultModel.setMapResult(1,"调用失败",res);
            return resultModel;
        }
    }

    //6、近30天事项申办量top8
    /**
     *设置近30天各项项业务量top8
     */
    @RequestMapping("topEightItemMonthCron")
    public Statistics topEightItemMonthCron(){
        Statistics resultModel=new Statistics();
        int EightTask=8;//代表前8
        try {
            int notWorkDay = DateUtil.getNotWorkDay(30);
            //如果查询数据为空
            List<TopEightTask> topEightTasks = statisticsService.topEightTask(DateUtil.getLateDate("yyyy-MM-dd HH:mm:ss",30 + notWorkDay));
            if (topEightTasks == null) {
                topEightTasks = new ArrayList<TopEightTask>();
                Map<String,String> map = redisUtil.hashGetP(Constants.ITEM_TOP_EIGHT);
                //设置前8事项的办理数
                for(String key: map.keySet()){
                    String value = map.get(key).toString();
                    TopEightTask topEightTask = new TopEightTask();
                    topEightTask.setNum(Integer.valueOf(value));
                    topEightTask.setTaskname(key);
                    topEightTasks.add(topEightTask);
                }
            }
            if (topEightTasks.size() != EightTask) {
                Map<String,String> map = redisUtil.hashGetP(Constants.ITEM_TOP_EIGHT);
                int index = EightTask - topEightTasks.size();
                for(String key: map.keySet()){
                    if(index!=0) {
                        String value = map.get(key).toString();
                        TopEightTask topEightTask = new TopEightTask();
                        topEightTask.setNum(Integer.valueOf(value));
                        topEightTask.setTaskname(key);
                        topEightTasks.add(topEightTask);
                        index--;
                    }else {
                        break;
                    }
                }
            }
            resultModel.setMapResult(0,"调用成功",topEightTasks);
            return resultModel;
        }catch (Exception e){
            logger.info("获取前八事项异常"+e.getMessage());
            resultModel.setMapResult(1,"调用失败");
            return resultModel;
        }
    }

    //7、近30天各业务区域申办量统计
    /**
     * 设置近30天热门业务区域业务量
     */
    @RequestMapping("zoneAcceptNumCron")
    public Statistics zoneAcceptNumCron(){
        Statistics resultModel = new Statistics();
        try {
            Map<String, Integer> temp = new HashMap<>();
            Map<String, Integer> map = statisticsService.areaApplyTotal();
            for (Map.Entry<String, Integer> m : map.entrySet()) {
                temp.put(m.getKey(),m.getValue()+Integer.valueOf(redisUtil.get(Constants.BASE_ACCEPT_NUM)));
            }
            resultModel.setMapResult(0,"调用成功",temp);
            return resultModel;
        }catch (Exception e) {
            logger.info("获取近30天热门业务区域业务量异常："+e.getMessage());
            resultModel.setMapResult(1,"调用失败");
            return resultModel;
        }
    }

    //8、近1天数据统计
    /**
     * 获取平均等待时间
     * @return
     */
    @RequestMapping("getWaitTime")
    public Statistics getWaitTime() {
        Statistics resultModel = new Statistics();
        //计算工作日
        int notWorkDay = DateUtil.getNotWorkDay(1);
        Date yesterday = DateUtil.getLateDate("yyyy-MM-dd HH:mm:ss", 1 + notWorkDay);
        Date currentDay = DateUtil.getCurrentDay();
        //Date yesterday = DateUtil.getLateDate("yyyy-MM-dd", 1 + notWorkDay);
        //获取平均等待时长分钟
        //long wminutes = announceNumberService.getList(month);
        Double wminutes = statisticsService.getWaitTime(currentDay,yesterday);
        wminutes = new BigDecimal(wminutes).setScale(2,BigDecimal.ROUND_DOWN).doubleValue();
        System.out.println("wminutes:"+wminutes);
        resultModel.setMapResult(0,"调用成功",wminutes);
        return resultModel;
    }
    /**
     * 获取平均受理时间
     * @return
     */
    @RequestMapping("getAccessTime")
    public Statistics getAccessTime() {
        Statistics resultModel = new Statistics();
        //计算工作日
        int notWorkDay = DateUtil.getNotWorkDay(1);
        Date yesterday = DateUtil.getLateDate("yyyy-MM-dd HH:mm:ss", 1 + notWorkDay);
        Date currentDay = DateUtil.getCurrentDay();
        //Date yesterday = DateUtil.getLateDate("yyyy-MM-dd", 1 + notWorkDay);
        //获取平均受理时长分钟
        //long aminutes = upProAcceptService.getList(month);
        double aminutes = statisticsService.getAccessTime(currentDay,yesterday);
        aminutes = new BigDecimal(aminutes).setScale(2,BigDecimal.ROUND_DOWN).doubleValue();
        System.out.println("aminutes:"+aminutes);
        resultModel.setMapResult(0,"调用成功",aminutes);
        return resultModel;
    }

    //9、近1天好差评率
    /**
     * 一天五个等级的满意度数量汇总
     */
    @RequestMapping("daySatisfactionCron")
    public Statistics daySatisfactionCron(){
        Statistics resultModel = new Statistics();
        Map<String, String> map = statisticsService.totalRate();
        resultModel.setMapResult(0,"调用成功",map);
        return resultModel;
    }

    //10、近30天各业务区域好差评得分排名（满分5分）
    /**
     * 近30天各业务区域好差评得分排名（满分5分）
     */
    @RequestMapping("zoneSatisfictionInit")
    public Statistics zoneSatisfictionInit(){
        Statistics resultModel = new Statistics();
        //Map<String,String> map = upProEvalService.specilEval();
        Map<String,String> map = statisticsService.scoreEval();
        resultModel.setMapResult(0,"调用成功",map);
        return resultModel;
    }

    //11、近10日文件柜放取人员对比图
    /**
     * 文件柜放件人类型最近10天对比，工作人员、办事人员
     */
    @RequestMapping("docLateTenReceiveTypeInit")
    public Statistics docLateTenReceiveTypeInit(){
        Statistics resultModel = new Statistics();
        Map<String, Object> lateTenMap = statisticsService.lateTen();//最近10天放件人类型对比
        resultModel.setMapResult(0,"调用成功",lateTenMap);
        return resultModel;
    }


    /**
     * 修改 系统参数表对应的实体
     * @return
     */
    @RequestMapping("updateSystemParam")
    public Statistics updateSystemParam(String openOrClose) {
        Statistics resultModel = new Statistics();
        List<SystemParam> openSimulateData = systemParamService.getSystemParamByName("openSimulateData");
        SystemParam systemParam = openSimulateData.get(0);
        systemParam.setParamValue(openOrClose);
        systemParamService.updateSystemParam(systemParam);
        resultModel.setMapResult(0,"调用成功",systemParamService.getSystemParamByName("openSimulateData").get(0));
        logger.info("updateSystemParam 返回参数resultModel{}", JSON.toJSONString(resultModel));
        return resultModel;
    }

}
